package br.com.sigw.persistence;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

import br.com.sigw.persistence.entitys.Entitys;

public class HibernateFacadeFactory {
	private static ThreadLocal<SessionHandle> threadLocal = new ThreadLocal<SessionHandle>();
	private static SessionFactory sessionFactory;
	
	private static SessionFactory getSessionFactory() throws Exception{
		if(sessionFactory == null){
			try{
				AnnotationConfiguration aConf = new AnnotationConfiguration();
				
				for(Class entity : Entitys.getMappedEntitys()){
					aConf.addAnnotatedClass(entity);
				}
				
				sessionFactory = aConf.configure().buildSessionFactory();
			}catch(Throwable error){
				new IllegalStateException("Erro ao criar uma SessionFactory...", error);
			}
		}
		
		return sessionFactory;
	}
	
	public static SessionHandle openSession() throws Exception{
		SessionHandle rootHnd = threadLocal.get();
		
		if(rootHnd == null){
			Session session = new SessionHandle(getSessionFactory().openSession());
			rootHnd = new SessionHandle(session);
			threadLocal.set(rootHnd);
			return rootHnd;
		}
		
		SessionHandle childHnd = new SessionHandle(rootHnd.getSession()); 
		return childHnd;
	}
	
	public static void closeSession(SessionHandle hnd){
		SessionHandle rootHnd = threadLocal.get();
		
		if(rootHnd != null && rootHnd.equals(hnd)){
			rootHnd.close();
			threadLocal.set(null);
		}
	}
}